package com.study.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study.context.BaseContext;
import com.study.dto.UserLoginDTO;
import com.study.entity.User;
import com.study.exception.UnauthorizedException;
import com.study.mapper.UserMapper;
import com.study.properties.WeChatProperties;
import com.study.service.UserService;
import com.study.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获得当前微信用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new RuntimeException("登陆失败");
        }
        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        //如果是新用户，自动完成注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     *
     * @param code 小程序端调用wx.login获取的code
     * @return
     */
    private String getOpenid(String code) {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /**
     * 根据id返回用户详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public User getUserById(Long userId) {
        log.info("根据id查询用户信息：{}", userId);
        User user = userMapper.getById(userId);
        return user;
    }

    /**
     * 更新用户信息
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {
        // 验证用户对象不为空
        if (user == null) {
            log.error("用户对象为空，无法更新用户信息");
            throw new IllegalArgumentException("用户信息修改失败");
        }

        Long userId = user.getId();
        //判断用户id是否为空或无效（例如，负数或零）
        if (userId == null || userId <= 0) {
            log.error("用户id为空或无效，用户信息修改失败");
            throw new IllegalArgumentException("用户信息修改失败");
        }

        //获取当前线程用户id
        Long currentId = BaseContext.getCurrentId();
        if(!userId.equals(currentId)){
            log.error("用户id不匹配，用户信息修改失败");
            throw new UnauthorizedException("更新失败，请检查客户端登陆状态");
        }
        //更新用户信息
        userMapper.updateUser(user);
    }
}
